/*
 * Copyright (c) 2013, Dennis Lee & Christopher Uyeda
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification
 * are permitted provided that the following conditions are met:
 * 		* Redistributions of source code must retain the above copyright notice,
 * 		  this list of conditions and the following disclaimer.
 * 		* Redistributions in binary form must reproduce the above copyright notice,
 * 		  this list of conditions and the following disclaimer in the documentation
 * 		  and/or other materials provided with the distribution.
 *		* Neither the name of the University of Hawaii at Manoa or the names of
 * 		  its contributors may be used to endorse or promote products derived from
 *		  this software without specific prior written permission.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package quickstats;

import java.awt.datatransfer.DataFlavor;        //drag and drop utility
import java.awt.dnd.DnDConstants;               //drag and drop utility
import java.awt.dnd.DropTarget;                 //drag and drop utility
import java.awt.dnd.DropTargetDropEvent;        //drag and drop utility
import java.io.BufferedReader;                  //to read file
import java.io.File;                            //to read file
import java.io.FileReader;                      //to read file
import java.util.List;                          //drag and drop utility
import java.util.StringTokenizer;               //to read file
import javax.swing.*;                           //ui utilities

/**
 * QuickStats
 * QuickStats is a GUI based drag and drop statistical calculator.
 * It handles Monovariate statistics and Bivariate statistics
 * @author Dennis Lee & Christopher Uyeda
 */
public class QuickStats extends javax.swing.JFrame {

    private MonovariateCalculator monovariatecalc;
    private BivariateCalculator bivariatecalc;
    private static String filepath;
    private static String filename;

    /**
     * Creates new form UI
     */
    public QuickStats() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel_Title = new javax.swing.JLabel();
        jPanel_drop = new javax.swing.JPanel();
        jLabel_drop = new javax.swing.JLabel();
        jPanel_output = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jButton_Monovariate = new javax.swing.JButton();
        jButton_Bivariate = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel_Title.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quickstats/quickstats.png"))); // NOI18N

        jLabel_drop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quickstats/Untitled-4.png"))); // NOI18N

        org.jdesktop.layout.GroupLayout jPanel_dropLayout = new org.jdesktop.layout.GroupLayout(jPanel_drop);
        jPanel_drop.setLayout(jPanel_dropLayout);
        jPanel_dropLayout.setHorizontalGroup(
            jPanel_dropLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel_dropLayout.createSequentialGroup()
                .add(31, 31, 31)
                .add(jLabel_drop)
                .addContainerGap(32, Short.MAX_VALUE))
        );
        jPanel_dropLayout.setVerticalGroup(
            jPanel_dropLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel_dropLayout.createSequentialGroup()
                .add(88, 88, 88)
                .add(jLabel_drop)
                .addContainerGap(107, Short.MAX_VALUE))
        );

        jTextArea_output.setColumns(20);
        jTextArea_output.setRows(5);
        jScrollPane1.setViewportView(jTextArea_output);

        org.jdesktop.layout.GroupLayout jPanel_outputLayout = new org.jdesktop.layout.GroupLayout(jPanel_output);
        jPanel_output.setLayout(jPanel_outputLayout);
        jPanel_outputLayout.setHorizontalGroup(
            jPanel_outputLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel_outputLayout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 434, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel_outputLayout.setVerticalGroup(
            jPanel_outputLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel_outputLayout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1)
                .addContainerGap())
        );

        jButton_Monovariate.setText("Compute Monovariate Stats");
        jButton_Monovariate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_MonovariateActionPerformed(evt);
            }
        });

        jButton_Bivariate.setText("Compute Bivariate Stats");
        jButton_Bivariate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_BivariateActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(26, 26, 26)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(jPanel_drop, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(6, 6, 6)
                                .add(jButton_Bivariate, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 205, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .add(18, 18, 18)
                                .add(jButton_Monovariate, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 205, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                            .add(jPanel_output, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                    .add(jLabel_Title))
                .addContainerGap(32, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(18, 18, 18)
                .add(jLabel_Title)
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(jPanel_drop, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jPanel_output, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jButton_Monovariate, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 47, Short.MAX_VALUE)
                    .add(jButton_Bivariate, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton_MonovariateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_MonovariateActionPerformed
        /* flags */
        boolean success = false;

        /* initialize calculator */
        this.monovariatecalc = new MonovariateCalculator();

        /* validation block */
        if ((filepath == null) || (!filepath.endsWith(".csv"))) {
            success = false;
            jTextArea_output.append("debug: filepath error \n");

        } else {

            /* load and read file into temp array */
            try {
                File f = new File(filepath);
                double[] tempOne = new double[10000];
                String line;
                int count = 0;

                BufferedReader br = new BufferedReader(new FileReader(filepath));

                while ((line = br.readLine()) != null) {
                    StringTokenizer st = new StringTokenizer(line, ",");
                    while (st.hasMoreTokens()) {
                        tempOne[count] = Double.parseDouble(st.nextToken());
                        count++;
                    }
                }
                br.close();

                double[] sampleOne = new double[count];
                System.arraycopy(tempOne, 0, sampleOne, 0, count);  // make a copy of the sample to get rid of trailing space    
                success = monovariatecalc.load(sampleOne);          // load the two samples

                if (success) {
                    jTextArea_output.append("debug: load ok \n");
                } else {
                    jTextArea_output.append("debug: load error \n");
                }

                success = monovariatecalc.compute();                    // run computations on the two samples

                if (success) {
                    jTextArea_output.append("debug: compute ok \n");
                } else {
                    jTextArea_output.append("debug: compute error \n");
                }

            } catch (Exception e) {
                success = false;
            }
        }

        if (success) {
            jTextArea_output.append("File read succesfully \n");
            jTextArea_output.append(monovariatecalc.toString());
        } else {
            jTextArea_output.append("There was an error trying to read the file \n");
        }
    }//GEN-LAST:event_jButton_MonovariateActionPerformed

    private void jButton_BivariateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_BivariateActionPerformed
        /* flags */
        boolean success = false;

        /* initialize calculator */
        this.bivariatecalc = new BivariateCalculator();

        /* validation block */
        if ((filepath == null) || (!filepath.endsWith(".csv"))) {
            success = false;

        } else {

            /* load and read file into temp array */
            try {
                File f = new File(filepath);
                double[] tempOne = new double[10000];
                double[] tempTwo = new double[10000];
                String line;
                int count = 0;

                BufferedReader br = new BufferedReader(new FileReader(filepath));

                while ((line = br.readLine()) != null) {
                    StringTokenizer st = new StringTokenizer(line, ",");
                    while (st.hasMoreTokens()) {
                        tempOne[count] = Double.parseDouble(st.nextToken());
                        tempTwo[count] = Double.parseDouble(st.nextToken());
                        count++;
                    }
                }
                br.close();

                double[] sampleOne = new double[count];
                double[] sampleTwo = new double[count];
                System.arraycopy(tempOne, 0, sampleOne, 0, count);  // make a copy of the first sample to get rid of trailing space    
                System.arraycopy(tempTwo, 0, sampleTwo, 0, count);  // make a copy of the second sample to get rid of trailing space

                success = bivariatecalc.load(sampleOne, sampleTwo); // load the two samples
                if (success) {
                    jTextArea_output.append("debug: load ok \n");
                } else {
                    jTextArea_output.append("debug: load error \n");
                }

                success = bivariatecalc.compute();                  // run computations on the two samples
                if (success) {
                    jTextArea_output.append("debug: compute ok \n");
                } else {
                    jTextArea_output.append("debug: compute error \n");
                }

            } catch (Exception e) {
                success = false;
            }
        }

        if (success) {
            jTextArea_output.setText("File read succesfully");
            jTextArea_output.append(bivariatecalc.toString());
        } else {
            jTextArea_output.setText("There was an error trying to read the file");
        }
    }//GEN-LAST:event_jButton_BivariateActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;


                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(QuickStats.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(QuickStats.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(QuickStats.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(QuickStats.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>


        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new QuickStats().setVisible(true);

                /* Create Drag and Drop Interface */
                jPanel_drop.setDropTarget(new DropTarget() {
                    public synchronized void drop(DropTargetDropEvent evt) {
                        try {
                            evt.acceptDrop(DnDConstants.ACTION_COPY);
                            List<File> droppedFiles = (List<File>) evt
                                    .getTransferable().getTransferData(
                                    DataFlavor.javaFileListFlavor);
                            for (File file : droppedFiles) {
                                jTextArea_output.setText("File loaded: " + file.getAbsolutePath());
                                jTextArea_output.append("\nReady to run");
                                filepath = file.getAbsolutePath();
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                });
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_Bivariate;
    private javax.swing.JButton jButton_Monovariate;
    private javax.swing.JLabel jLabel_Title;
    private javax.swing.JLabel jLabel_drop;
    private static javax.swing.JPanel jPanel_drop;
    private javax.swing.JPanel jPanel_output;
    private javax.swing.JScrollPane jScrollPane1;
    private static final javax.swing.JTextArea jTextArea_output = new javax.swing.JTextArea();
    // End of variables declaration//GEN-END:variables
}
